import {
    APP_ID,
    CLIENT,
    PlATFORM,
    TOKEN_KEY
} from "../config";
import {
    ResultMessageEnum
} from '../config/resultMessageEnum'
import LocalStorage from '../utils/localStorage'
import {
    loginController
} from "../utils/login"
let requestQueue = [];
let isRefreshingToken = false;

let loadingCount = 0;

const tryStartLoading = () => {
    if (loadingCount === 0) {
        tt.showLoading();
    }
    loadingCount++;
}

const tryHideLoading = () => {
    loadingCount--;
    if (loadingCount === 0) {
        tt.hideLoading();
    }
}


export const request = (options) => {
    options.method && (options.method = options.method.toUpperCase())
    options.loading ??= true;
    return new Promise((resolve, reject) => {
        options.loading && tryStartLoading()
        tt.request({
            url: options.url,
            method: options.method || "GET",
            data: options.data || {},
            header: Object.assign({}, options.header, {
                'content-type': "application/json",
                'authorization': LocalStorage.getItem(TOKEN_KEY),
                'client': CLIENT,
                'platform': PlATFORM,
                "app-id": APP_ID
            }),
            success: (res) => {
                if (res.statusCode == 200 && res.data.code == 200) {
                    resolve(res.data)
                } else if (res.statusCode == 200 && res.data.code !== 200) {
                    reject(res.data.msg)
                } else {
                    reject(res.data.error)
                }
            },
            fail: (err) => {
                reject(err)
            },
            complete: () => {
                options.loading && tryHideLoading()
            }
        });
    })
}



// 封装的请求函数  
export async function http(options) {
    options.needToken ??= true;
    console.log(options.needToken)
    if (!options.needToken) {
        return request(options);
    }
    // 检查token是否有效，这里假设你有一个函数来判断  
    let isTokenExpired = await checkTokenExpired();
    if (isTokenExpired) {
        // 如果token失效，将请求添加到队列中  
        //    let cb= addQueue();
        // 如果当前没有在刷新token，则开始刷新  
        return new Promise((resolve) => {
            requestQueue.push(() => request(options).then(resolve))
            if (!isRefreshingToken) {
                tryRefreshToken();
            }
        })
    } else {
        // 如果token有效，直接发送请求  
        return request(options);
    }
}



async function tryRefreshToken() {
    if (!isRefreshingToken) {
        isRefreshingToken = true;
        await refreshToken();
        isRefreshingToken = false;
        while (requestQueue.length > 0) {
            let _request = requestQueue.shift();
            _request();
        }
    }
}

async function refreshToken() {
    await loginController.login(true)
}

function checkTokenExpired() {
    // 这里应该添加实际的逻辑来检查token是否过期  
    // 比如检查存储的token是否存在，是否超过了有效期等  
    return false; // 假设token已过期返回true，否则返回false  
}

// 更新token的函数（示例）  
function updateToken(newToken) {
    // 这里应该添加实际的逻辑来更新存储的token  
    // 比如将新的token保存到本地存储或全局变量中  
}